﻿using System.IO;
using System.Threading.Tasks;
using RestSharp;
using RestSharp.Authenticators;
using TweetSharp;

namespace WhallaToolkit.ShareServices.Helpers
{
    public static class TweetSharpExtensions
    {
        public static async Task<OAuthRequestToken> GetRequestTokenAsync(this TwitterService service, string ConsumerKey, string ConsumerSecret)
        {
            TaskCompletionSource<bool> cts = new TaskCompletionSource<bool>();
            var client = new RestClient("https://api.twitter.com/");
            client.Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret);
            var request = new RestRequest("oauth/request_token");
            OAuthRequestToken resp = new OAuthRequestToken();
            client.ExecuteAsync(request, response =>
            {
                var _oAuthToken = GetQueryParameter(response.Content, "oauth_token");
                var _oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
                string authorizeUrl = "https://api.twitter.com/oauth/authorize" + "?oauth_token=" + _oAuthToken + "&style=mobile";
                resp.OAuthCallbackConfirmed = true;
                resp.Token = _oAuthToken;
                resp.TokenSecret = _oAuthTokenSecret;
                cts.SetResult(true);
            });
            await cts.Task;

            return resp;
        }

        public static async Task<OAuthAccessToken> GetAccessTokenAsync(this TwitterService service, string ConsumerKey, string ConsumerSecret, OAuthRequestToken requestToken, string verifier)
        {
            /*Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
                     oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
                     oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
                     oauth_signature_method="HMAC-SHA1",
                     oauth_timestamp="1318467427",
                     oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
                     oauth_version="1.0"'*/

            TaskCompletionSource<bool> cts = new TaskCompletionSource<bool>();
            var client = new RestClient("https://api.twitter.com/");
            client.Authenticator = OAuth1Authenticator.ForAccessToken(ConsumerKey, ConsumerSecret, requestToken.Token, requestToken.TokenSecret, verifier);
            var request = new RestRequest("oauth/access_token");
            request.Method = Method.POST;
            OAuthAccessToken resp = new OAuthAccessToken();
            client.ExecuteAsync(request, response =>
            {
                var _oAuthToken = GetQueryParameter(response.Content, "oauth_token");
                var _oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
                resp.Token = _oAuthToken;
                resp.TokenSecret = _oAuthTokenSecret;
                cts.SetResult(true);
            });
            await cts.Task;
            return resp;
        }

        public static string GetQueryParameter(string inputURL, string parameterName)
        {
            string input = inputURL.Replace('?', '&');
            string result = null;
            foreach (string item in input.Split('&'))
            {
                var parts = item.Split('=');
                if (parts[0] == parameterName)
                {
                    result = parts[1];
                }
            }

            return result;
        }

    }

    public static class Extensions
    {
        public static MemoryStream ConvertStreamToMemoryStream(this Stream stream)
        {
            MemoryStream memoryStream = new MemoryStream();

            if (stream != null)
            {

                byte[] buffer = ReadFully(stream);

                if (buffer != null)
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    binaryWriter.Write(buffer);
                }
            }
            return memoryStream;
        }

        public static byte[] ReadFully(this Stream input)
        {

            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}
